from rest_framework.views import exception_handler
from rest_framework import status
from rest_framework.exceptions import APIException, Throttled

from utils.response import Code


class BadParamsException(APIException):
    # status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    # default_detail = _('A server error occurred.')
    # default_code = 'error'

    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = '参数错误~~'
    default_code = Code.BadParams


class TokenException(APIException):
    status_code = status.HTTP_400_BAD_REQUEST
    default_detail = 'Token错误~~'
    default_code = Code.BadParams


class UnAuthException(APIException):
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = '未授权~~'
    default_code = Code.UnAuth


class NotFoundException(APIException):
    status_code = status.HTTP_404_NOT_FOUND
    default_detail = '未找到~~'
    default_code = Code.NotFound


class MethodErrorException(APIException):
    status_code = status.HTTP_405_METHOD_NOT_ALLOWED
    default_detail = '方法错误~~'
    default_code = Code.MethodError


class ServerErrorException(APIException):
    status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    default_detail = '服务器错误~~'
    default_code = Code.ServerError


class ThrottledException(APIException):
    status_code = status.HTTP_429_TOO_MANY_REQUESTS
    default_detail = '访问频率过快~~'
    default_code = Code.BadParams


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    # {'category_id': [ErrorDetail(string='请填写合法的整数值。', code='invalid')]}
    # {'detail': ErrorDetail(string='分类错误~~', code=1000)}
    try:
        msg = response.data.pop('detail')
    except (KeyError, AttributeError) as e:
        msg = '出错咯~~'
    if response is not None:
        response.data['msg'] = msg
        if response.status_code == 400:
            response.data['code'] = Code.BadParams

        elif response.status_code == 401:
            response.data['code'] = Code.UnAuth

        elif response.status_code == 404:
            response.data['code'] = Code.NotFound

        elif response.status_code == 403:
            response.data['code'] = Code.CSRF

        elif response.status_code == 405:
            response.data['code'] = Code.MethodError

        elif response.status_code >= 500:
            response.data['code'] = Code.ServerError

        elif response.status_code >= 429:
            response.data['code'] = Code.BadParams
        response.status_code = 200  # 所有200 根据code分类
    return response
